"use client";

import { useState, useTransition, useEffect } from "react";
import { useQRCode } from 'next-qrcode';
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";

const STORAGE_KEY = "yyds-token";
const DEFAULT_TOKEN = "6843d1676c26b";

const CODES = [
  "SQ-06-01-33C",
  "SQ-07-01-28C",
  "SQ-07-01-26A",
];

export default function QrcodeGenerator({ generateSDK }) {
  const [code, setCode] = useState(CODES[0]);
  const [token, setToken] = useState(DEFAULT_TOKEN);
  const [sdk, setSdk] = useState("");
  const [isPending, startTransition] = useTransition();
  const [dialogOpen, setDialogOpen] = useState(false);

  const { Canvas } = useQRCode();

  // 组件挂载时读取本地保存的 token
  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      setToken(saved);
    } else {
      localStorage.setItem(STORAGE_KEY, DEFAULT_TOKEN);
    }
  }, []);

  // token 变化时同步到本地
  const handleTokenChange = (e) => {
    const value = e.target.value;
    setToken(value);
    if (typeof window !== "undefined") {
      localStorage.setItem(STORAGE_KEY, value);
    }
  };

  const onGenerate = () => {
    startTransition(async () => {
      try {
        setSdk("");
        const result = await generateSDK(code, token);
        setSdk(result);
      } catch (e) {
        console.error(e);
        setDialogOpen(true);
      }
    });
  };

  return (
    <div className="p-4 space-y-4 max-w-sm mx-auto">

      {/* ResCode 选择器 */}
      <div className="space-y-1">
        <Label htmlFor="rescode">选择楼层</Label>
        <Select value={code} onValueChange={setCode}>
          <SelectTrigger id="rescode">
            <SelectValue placeholder="选择 ResCode" />
          </SelectTrigger>
          <SelectContent>
            {CODES.map((c) => (
              <SelectItem key={c} value={c}>
                {c}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Token 输入框 */}
      <div className="space-y-1">
        <Label htmlFor="token-input">接口 Token</Label>
        <Input
          id="token-input"
          placeholder="输入接口 Token"
          value={token}
          onChange={handleTokenChange}
        />
      </div>

      {/* 错误弹窗，允许用户输入新的 token 并重试 */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>接口鉴权失败</DialogTitle>
            <DialogDescription>
              当前 Token 可能已失效，请输入新的 Token 后重新生成二维码。
            </DialogDescription>
          </DialogHeader>

          <Input
            placeholder="新的 Token"
            value={token}
            onChange={handleTokenChange}
          />

          <DialogFooter className="pt-4">
            <Button variant="outline" onClick={() => setDialogOpen(false)}>
              取消
            </Button>
            <Button
              onClick={() => {
                setDialogOpen(false);
                onGenerate();
              }}
            >
              重新生成
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Button className="w-full" disabled={isPending} onClick={onGenerate}>
        {isPending ? "生成中…" : "生成二维码"}
      </Button>

      {sdk && (
        <div className="flex flex-col items-center space-y-2">
          <Canvas text={sdk} size={200} />
          <textarea
            readOnly
            className="w-full text-xs p-2 border rounded"
            rows={4}
            value={sdk}
          />
        </div>
      )}
    </div>
  );
}